package com.cj.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cj.reggie.common.R;
import com.cj.reggie.entity.User;
import com.cj.reggie.service.UserService;
import com.cj.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        // 获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            // 生成随机的4为验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code = {}", code);
            // 调用阿里云提供的短信服务API完成发送短信
//            SMSUtils.sendMessage("瑞吉买卖", "", phone, code);
            // 验证码保存到session中
//            session.setAttribute(phone, code);
            // 将验证码存储到Redis中设置时间5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("发送短信成功");
        }
        // 需要将审核从的验证码保存到Session中
        return R.error("发送短信失败");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
//        http://localhost:8080/front/page/login.html
        log.info(map.toString());
        String phone=null;
        String code =null;
        try {
            // 获取手机号
            phone = map.get("phone").toString();
            // 获取验证码
            code = map.get("code").toString();
        }catch (NullPointerException e){
            R.error("数据错误");
        }
        // Session中获取保存的验证码
//        Object codeInSession = session.getAttribute(phone);
        // 从Redis中获取验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        // 进行比对（Session中保存验证码进行对比）
        if (codeInSession!=null&&codeInSession.equals(code)){
            // 如果能够对比成功，说明登录成功
            // 判断手机号是否新用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user==null){
                // 新用户进行注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            // 如果用户登录成功，删除Redis中缓存的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");
    }
}
